package com.szeastroc.controller.system;

import com.github.pagehelper.PageInfo;
import com.szeastroc.base.controller.BaseController;
import com.szeastroc.bean.system.SystemResource;
import com.szeastroc.bean.system.ZTreeNode;
import com.szeastroc.service.system.SystemResourceService;
import com.szeastroc.utils.LayerTableDataUtil;
import com.szeastroc.utils.Result4Ajax;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by jie on 2018/1/13.
 */
@Controller
@RequestMapping("/systemResource")
public class SystemResourceController extends BaseController{

    @Autowired
    private SystemResourceService systemResourceService;


    @GetMapping("/index")
    public String index(){
        return "system/system_resource.html";
    }

    @PostMapping("/getResource")
    @ResponseBody
    public LayerTableDataUtil getResource(Model model, Integer page, Integer limit){
        PageInfo<SystemResource> pageinfo = systemResourceService.selectPage(page,limit);
        LayerTableDataUtil data = new LayerTableDataUtil(pageinfo.getTotal(),pageinfo.getList());
        return data;
    }


    @GetMapping("/editResource")
    public String editResource(Model model,Integer roleId){
        model.addAttribute("roleId",roleId);
        return "system/system_resource_tree.html";
    }

    @PostMapping("/getRoleResource")
    @ResponseBody
    public List<ZTreeNode> getRoleResource(Integer roleId){
        List<ZTreeNode> list = systemResourceService.getAllSystemResourceTreeByRoleId(roleId);
        return list;
    }


    @PostMapping("saveRoleResources")
    @ResponseBody
    public Result4Ajax saveRoleResources(String resourceIds,Integer roleId){
        try {
            systemResourceService.saveRoleResources(resourceIds,roleId);
            return super.success();
        } catch (Exception e) {
            logger.error("保存角色权限错误",e);
            return super.error();
        }
    }

    @PostMapping("saveResourcesStatus")
    @ResponseBody
    public Result4Ajax saveResourcesStatus(Integer resourceId,Integer status){
        try {
            if(resourceId ==null || status == null){
                return super.error(501,"缺少参数!");
            }
            systemResourceService.saveResourcesStatus(resourceId,status);
            return super.success();
        } catch (Exception e) {
            logger.error("保存角色权限错误",e);
            return super.error();
        }
    }
}
